import 'package:flutter/material.dart';
import '../models/community_post.dart';
import '../models/comment.dart';
import '../services/community_service.dart';

class CommunityProvider with ChangeNotifier {
  final CommunityService _communityService = CommunityService();

  // 帖子列表相关
  List<CommunityPost> _posts = [];
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;
  int _total = 0;
  String? _errorMessage;

  // 帖子详情相关
  CommunityPost? _currentPost;
  List<Comment> _comments = [];
  bool _isLoadingComments = false;
  int _currentCommentPage = 1;
  bool _hasMoreComments = true;

  // 热门帖子
  List<CommunityPost> _hotPosts = [];
  bool _isLoadingHotPosts = false;

  // 用户相关帖子
  List<CommunityPost> _userPosts = [];
  List<CommunityPost> _favoritePosts = [];

  // Getters
  List<CommunityPost> get posts => _posts;
  bool get isLoading => _isLoading;
  bool get hasMore => _hasMore;
  int get total => _total;
  String? get errorMessage => _errorMessage;

  CommunityPost? get currentPost => _currentPost;
  List<Comment> get comments => _comments;
  bool get isLoadingComments => _isLoadingComments;
  bool get hasMoreComments => _hasMoreComments;

  List<CommunityPost> get hotPosts => _hotPosts;
  bool get isLoadingHotPosts => _isLoadingHotPosts;

  List<CommunityPost> get userPosts => _userPosts;
  List<CommunityPost> get favoritePosts => _favoritePosts;

  /// 获取社区帖子列表
  Future<void> loadPosts({
    bool refresh = false,
    String? title,
    String? tags,
    String? location,
  }) async {
    if (refresh) {
      _currentPage = 1;
      _hasMore = true;
      _posts.clear();
    }

    if (_isLoading || !_hasMore) return;

    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final result = await _communityService.getCommunityPosts(
        page: _currentPage,
        size: 10,
        title: title,
        tags: tags,
        location: location,
      );


      if (result['success']) {
        final newPosts = result['data'] as List<CommunityPost>;
        _total = result['total'] ?? 0;

        if (refresh) {
          _posts = newPosts;
        } else {
          _posts.addAll(newPosts);
        }

        _currentPage++;
        _hasMore = newPosts.length >= 10;
      } else {
        _errorMessage = result['message'];
      }
    } catch (e) {
      _errorMessage = '加载失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 获取帖子详情
  Future<void> loadPostDetail(int postId) async {
    try {
      // 增加阅读量
      _communityService.incrementReadCount(postId);

      final result = await _communityService.getCommunityPostDetail(postId);
      if (result['success']) {
        _currentPost = result['data'];
        notifyListeners();
      }
    } catch (e) {
    }
  }

  /// 发布新帖子
  Future<bool> createPost({
    required String title,
    required String content,
    List<String>? tags,
    String? location,
    List<String>? imageUrls,
  }) async {
    try {
      final result = await _communityService.createCommunityPost(
        title: title,
        content: content,
        tags: tags,
        location: location,
        imageUrls: imageUrls,
      );

      if (result['success']) {
        // 刷新帖子列表
        await loadPosts(refresh: true);
        return true;
      } else {
        _errorMessage = result['message'];
        notifyListeners();
        return false;
      }
    } catch (e) {
      _errorMessage = '发布失败: $e';
      notifyListeners();
      return false;
    }
  }

  /// 点赞/取消点赞帖子
  Future<void> toggleLikePost(int postId) async {
    try {
      final result = await _communityService.toggleLikePost(postId);
      if (result['success']) {
        final data = result['data'];
        final isLiked = data['isLiked'] as bool;
        final likeCount = data['likeCount'] as int;

        // 更新列表中的帖子
        _updatePostInList(postId, (post) {
          return post.copyWith(
            isLiked: isLiked,
            likeCount: likeCount,
          );
        });

        // 更新当前帖子详情
        if (_currentPost?.id == postId) {
          _currentPost = _currentPost!.copyWith(
            isLiked: isLiked,
            likeCount: likeCount,
          );
        }

        notifyListeners();
      }
    } catch (e) {
    }
  }

  /// 收藏/取消收藏帖子
  Future<void> toggleFavoritePost(int postId) async {
    try {
      final result = await _communityService.toggleFavoritePost(postId);
      if (result['success']) {
        final data = result['data'];
        final isFavorited = data['isFavorited'] as bool;

        // 更新列表中的帖子
        _updatePostInList(postId, (post) {
          return post.copyWith(isFavorited: isFavorited);
        });

        // 更新当前帖子详情
        if (_currentPost?.id == postId) {
          _currentPost = _currentPost!.copyWith(isFavorited: isFavorited);
        }

        notifyListeners();
      }
    } catch (e) {
    }
  }

  /// 获取帖子评论
  Future<void> loadComments(int postId, {bool refresh = false}) async {
    if (refresh) {
      _currentCommentPage = 1;
      _hasMoreComments = true;
      _comments.clear();
    }

    if (_isLoadingComments || !_hasMoreComments) return;

    _isLoadingComments = true;
    notifyListeners();

    try {
      final result = await _communityService.getPostComments(
        postId: postId,
        page: _currentCommentPage,
        size: 20,
      );

      if (result['success']) {
        final newComments = result['data'] as List<Comment>;

        if (refresh) {
          _comments = newComments;
        } else {
          _comments.addAll(newComments);
        }

        _currentCommentPage++;
        _hasMoreComments = newComments.length >= 20;
      }
    } catch (e) {
    } finally {
      _isLoadingComments = false;
      notifyListeners();
    }
  }

  /// 发表评论
  Future<bool> addComment({
    required int postId,
    required String content,
    int? parentId,
  }) async {
    try {
      final result = await _communityService.addComment(
        postId: postId,
        content: content,
        parentId: parentId,
      );

      if (result['success']) {
        // 刷新评论列表
        await loadComments(postId, refresh: true);
        
        // 更新帖子评论数
        _updatePostInList(postId, (post) {
          return post.copyWith(commentCount: post.commentCount + 1);
        });

        if (_currentPost?.id == postId) {
          _currentPost = _currentPost!.copyWith(
            commentCount: _currentPost!.commentCount + 1,
          );
        }

        notifyListeners();
        return true;
      } else {
        _errorMessage = result['message'];
        notifyListeners();
        return false;
      }
    } catch (e) {
      _errorMessage = '评论失败: $e';
      notifyListeners();
      return false;
    }
  }

  /// 点赞/取消点赞评论
  Future<void> toggleLikeComment(int commentId) async {
    try {
      final result = await _communityService.toggleLikeComment(commentId);
      if (result['success']) {
        final data = result['data'];
        final likeCount = data['likeCount'] as int;

        // 更新评论列表
        final index = _comments.indexWhere((comment) => comment.id == commentId);
        if (index != -1) {
          _comments[index] = _comments[index].copyWith(
            likeCount: likeCount,
            // 注意：Comment模型可能需要添加isLiked字段
          );
          notifyListeners();
        }
      }
    } catch (e) {
    }
  }

  /// 获取热门帖子
  Future<void> loadHotPosts({String type = 'read'}) async {
    _isLoadingHotPosts = true;
    notifyListeners();

    try {
      final result = await _communityService.getHotPosts(
        limit: 10,
        type: type,
      );


      if (result['success']) {
        _hotPosts = result['data'] ?? [];
      } else {
        _hotPosts = [];
      }
    } catch (e) {
      _hotPosts = [];
    } finally {
      _isLoadingHotPosts = false;
      notifyListeners();
    }
  }

  /// 获取用户发布的帖子
  Future<void> loadUserPosts() async {
    try {
      final result = await _communityService.getUserPosts();
      if (result['success']) {
        _userPosts = result['data'];
        notifyListeners();
      }
    } catch (e) {
    }
  }

  /// 获取用户收藏的帖子
  Future<void> loadFavoritePosts() async {
    try {
      final result = await _communityService.getUserFavorites();
      if (result['success']) {
        _favoritePosts = result['data'];
        notifyListeners();
      }
    } catch (e) {
    }
  }

  /// 删除帖子
  Future<bool> deletePost(int postId) async {
    try {
      final result = await _communityService.deleteCommunityPost([postId]);
      if (result['success']) {
        // 从列表中移除帖子
        _posts.removeWhere((post) => post.id == postId);
        _userPosts.removeWhere((post) => post.id == postId);
        _favoritePosts.removeWhere((post) => post.id == postId);
        _hotPosts.removeWhere((post) => post.id == postId);
        
        notifyListeners();
        return true;
      } else {
        _errorMessage = result['message'];
        notifyListeners();
        return false;
      }
    } catch (e) {
      _errorMessage = '删除失败: $e';
      notifyListeners();
      return false;
    }
  }

  /// 清除错误信息
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  /// 重置当前帖子
  void clearCurrentPost() {
    _currentPost = null;
    _comments.clear();
    _currentCommentPage = 1;
    _hasMoreComments = true;
    notifyListeners();
  }

  /// 更新列表中的帖子
  void _updatePostInList(int postId, CommunityPost Function(CommunityPost) updater) {
    // 更新主列表
    final index = _posts.indexWhere((post) => post.id == postId);
    if (index != -1) {
      _posts[index] = updater(_posts[index]);
    }

    // 更新热门列表
    final hotIndex = _hotPosts.indexWhere((post) => post.id == postId);
    if (hotIndex != -1) {
      _hotPosts[hotIndex] = updater(_hotPosts[hotIndex]);
    }

    // 更新用户帖子列表
    final userIndex = _userPosts.indexWhere((post) => post.id == postId);
    if (userIndex != -1) {
      _userPosts[userIndex] = updater(_userPosts[userIndex]);
    }

    // 更新收藏列表
    final favoriteIndex = _favoritePosts.indexWhere((post) => post.id == postId);
    if (favoriteIndex != -1) {
      _favoritePosts[favoriteIndex] = updater(_favoritePosts[favoriteIndex]);
    }
  }
}